<?php 
class kdtrace_dnjex extends Controller {
	
	function track( $tracknum , $lang = ""){
		
		$url 	 = "http://www.dnjexpress.com/showstatee.asp?orderno=" . $tracknum ;
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Referer: http://www.dnjexpress.com/',
			'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36' 
		));
		$result = curl_exec($ch);
        curl_close($ch);
		$rtndata = array('tracknum'=>$tracknum,'header'=>array(),'err'=>array(),'eventList'=>array());

		if( strpos($result , "Shipment Query Error")>0 ){
			$rtndata['err']['errcode'] = '1';
			return $rtndata;
		}
		$result = $this->skipSpaces($result);
		$rtndata['err']['errcode'] = '0';
		
		$w1 = strpos($result , "td align=center>Detail</td>" );
		$w2 = strpos($result , '</table>' ,$w1);
		$rhtm = substr($result , $w1 , $w2 - $w1);
		$rhtm = str_replace("&nbsp;" , " " , $result);

		if(preg_match("/>Current Status<\/span><\/td> <td><span class\=\"txt\">(.+?)<\/span>/i", $rhtm, $matches) == 1){
			$rtndata['header']['DetailStatus']		= $matches[1];
		};
		if(strpos($rhtm , ">Delivered on</span></td>")>0){
			$rtndata['header']['isDelivered']	= true;
		}else{
			$rtndata['header']['isDelivered']	= false;
		};
		
		if(preg_match("/>Origin<\/span><\/td> <td width\=\d*%><span class\=\"txt\">(.+?)<\/span>/i", $rhtm, $matches) == 1){
			$rtndata['header']['shipFrom']		= $matches[1];
		};
		if(preg_match("/>Destination<\/span><\/td> <td width\=\d*%><span class\=\"txt\">(.+?)<\/span>/i", $rhtm, $matches) == 1){
			$rtndata['header']['shipTo']		= $matches[1];
		};

		$w1 = strpos($result , '<span class="txt">Activity</span></td>' );
		$w2 = strpos($result , '</table>' ,$w1);
		$bdhtm = substr($result , $w1 , $w2 - $w1);
		$bdhtm = str_replace("&nbsp;" , " " , $bdhtm);

		preg_match_all("/<td><span class\=\"txt\">(.+?)<\/span><\/td> <td><span class\=\"txt\">(.+?)<\/span><\/td> <td><span class\=\"txt\">(.+?)<\/span><\/td>/i", $bdhtm, $matches);

		$count = count($matches[0]);
		if($count>0){
			for($i=0 ; $i < $count ; $i++){
				//$this->skipSpaces($matches[1][$i])
				$tt =  strtotime( trim($matches[2][$i]) );
				$rtndata['eventList'][$i] = array(
					"date"			=> date('Y-m-d',$tt),
					"time"			=> date('h:i:s',$tt),
					"utime"			=> $tt,
					"status"		=> trim($matches[3][$i]),
					"location"		=> trim($matches[1][$i])
				);
			}
		}

		$rtndata['eventList'] = array_reverse( $rtndata['eventList'] );
		return $rtndata;
	}
	function skipSpaces($t){
			return  trim(preg_replace('/\s{2,}/', ' ', $t));
	}
	
}

?>